<template>
  <div>
    <div>
      <Card v-for="(image, index) in imageList" :key="index" class="image-card">
        <div class="image-box" @click="toggleSelect(image, index)">
          <img :src="yunPath + image.key"/>
        </div>
        <span slot="extra">
          <Checkbox v-model="image.checked" @on-change="isChecked => toggleCheck(image, index, isChecked)"></Checkbox>
        </span>
      </Card>
    </div>
    <Divider></Divider>
    <div style="text-align: right;">
      <Button @click="cancelClick()">取消</Button>
      <Button type="primary" @click="okClick()" style="margin-left: 10px;">确定</Button>
    </div>
  </div>
</template>

<script>
export default {
  name: "ImpProductImgSelect",
  props: {
    productCode: {type: String, required: true, default: ""},
    isSingleSelect: {type: Boolean, default: true},
  },
  data() {
    return {
      yunPath: this.$store.getters.aliImgPrefix,
      imageList: [],
    };
  },
  methods: {
    okClick() {
      let selectedImages = this.imageList.filter(element => element.checked).map(element => element.key.replace("products/", ""));
      if(selectedImages.length < 1) {
        this.$Message.warning({content: "请选择图片！", duration: 40000, closable: true});
        return false;
      }
      this.$emit("okClick", selectedImages);
    },
    cancelClick() {
      this.$emit("cancelClick");
    },
    toggleSelect(image, index) {
      if(this.isSingleSelect) {
        image.checked = !image.checked;
        //其他图片取消选中
        for(let i=0; i<this.imageList.length; i++) {
          if(i != index) {
            this.imageList[i].checked = false;
          }
        }
      }else{
        image.checked = !image.checked;
      }
    },
    toggleCheck(image, index, isChecked) {
      if(this.isSingleSelect) {
        //其他图片取消选中
        for (let i = 0; i < this.imageList.length; i++) {
          if (i != index) {
            this.imageList[i].checked = false;
          }
        }
      }
    }
  },
  mounted() {
    // console.log("impProduct image select");
  },
  watch: {
    productCode() {
      let params = {pCode: this.productCode};
      this.$Spin.show();
      this.$apiImpProduct.queryImagesByPCode(params).then(response => {
        this.$Spin.hide();
        this.imageList.splice(0);
        if(response.success) {
          for(let imageKey of response.result) {
            this.imageList.push({key: imageKey, checked: false});
          }
        }else{
          this.$Message.error(response.errorMessage);
        }
      }).catch(() => {
        this.$Message.error("查询图片失败！");
        this.imageList.splice(0);
      });
    }
  }
}
</script>

<style scoped lang="less">
@import  (once,optional)  "../css/base.less";
.image-card {
  width: 200px;
  height: 200px;
  display: inline-block;
  margin: 10px;
}
.image-box {
  width: 168px;
  height: 168px;
  line-height: 168px;
  text-align: center;
  img {
    max-width: 100%;
    max-height: 100%;
    vertical-align: middle;
  }
}
</style>
